import { ref, computed, onMounted, onUnmounted } from "vue";
import { useRouter } from "vue-router";
import { useAppStore } from "@/stores/app";
import { useUserStore } from "@/stores/user";
import { systemApi } from "@/api/services";
import type {
  AppInfo,
  SystemStatus,
  Notification,
  Announcement,
} from "@/types/app";
import { APP_CONFIG, STORAGE_KEYS, ROUTES } from "@/constants";
import { formatFileSize, formatTimestamp } from "@/utils";

/**
 * 应用相关的组合式函数
 */
export function useApp() {
  const router = useRouter();
  const appStore = useAppStore();
  const userStore = useUserStore();

  // 响应式状态
  const isLoading = ref(false);
  const error = ref<string | null>(null);
  const isOnline = ref(navigator.onLine);
  const lastHeartbeat = ref<Date | null>(null);
  const heartbeatInterval = ref<number | null>(null);

  // 计算属性
  const appInfo = computed(() => appStore.appInfo);
  const systemStatus = computed(() => appStore.systemStatus);
  const notifications = computed(() => appStore.notifications);
  const announcements = computed(() => appStore.announcements);
  const unreadNotifications = computed(() => appStore.unreadNotifications);
  const unreadAnnouncements = computed(() => appStore.unreadAnnouncements);
  const isMaintenanceMode = computed(() => appStore.isMaintenanceMode);
  const systemSettings = computed(() => appStore.systemSettings);
  const featureLimits = computed(() => appStore.featureLimits);

  // 未读消息数量
  const unreadCount = computed(() => {
    return unreadNotifications.value.length + unreadAnnouncements.value.length;
  });

  // 系统健康状态
  const systemHealth = computed(() => {
    const status = systemStatus.value;
    if (!status) return "unknown";

    const { cpu, memory, disk } = status;
    if (cpu > 90 || memory > 90 || disk > 95) return "critical";
    if (cpu > 70 || memory > 70 || disk > 85) return "warning";
    return "healthy";
  });

  /**
   * 初始化应用
   */
  const initializeApp = async () => {
    try {
      isLoading.value = true;
      error.value = null;

      // 并行加载应用信息和系统状态
      const [appInfoResult, systemStatusResult] = await Promise.allSettled([
        loadAppInfo(),
        loadSystemStatus(),
      ]);

      // 检查结果
      if (appInfoResult.status === "rejected") {
        console.error("Failed to load app info:", appInfoResult.reason);
      }

      if (systemStatusResult.status === "rejected") {
        console.error(
          "Failed to load system status:",
          systemStatusResult.reason,
        );
      }

      // 如果用户已登录，加载用户相关数据
      if (userStore.isAuthenticated) {
        await Promise.allSettled([
          loadNotifications(),
          loadAnnouncements(),
          loadSystemSettings(),
        ]);
      }

      // 启动心跳检测
      startHeartbeat();

      return { success: true };
    } catch (err: any) {
      error.value = err.message || "应用初始化失败";
      return { success: false, message: error.value };
    } finally {
      isLoading.value = false;
    }
  };

  /**
   * 加载应用信息
   */
  const loadAppInfo = async () => {
    try {
      const response = await appApiService.getAppInfo();

      if (response.success) {
        appStore.setAppInfo(response.data);
        return { success: true, data: response.data };
      } else {
        error.value = response.message || "加载应用信息失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "加载应用信息失败";
      return { success: false, message: error.value };
    }
  };

  /**
   * 加载系统状态
   */
  const loadSystemStatus = async () => {
    try {
      const response = await appApiService.getSystemStatus();

      if (response.success) {
        appStore.setSystemStatus(response.data);
        lastHeartbeat.value = new Date();
        return { success: true, data: response.data };
      } else {
        error.value = response.message || "加载系统状态失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "加载系统状态失败";
      return { success: false, message: error.value };
    }
  };

  /**
   * 加载通知列表
   */
  const loadNotifications = async (page: number = 1, limit: number = 20) => {
    try {
      const response = await appApiService.getNotifications({ page, limit });

      if (response.success) {
        if (page === 1) {
          appStore.setNotifications(response.data.notifications);
        } else {
          appStore.addNotifications(response.data.notifications);
        }

        return { success: true, data: response.data };
      } else {
        error.value = response.message || "加载通知失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "加载通知失败";
      return { success: false, message: error.value };
    }
  };

  /**
   * 加载公告列表
   */
  const loadAnnouncements = async (page: number = 1, limit: number = 10) => {
    try {
      const response = await appApiService.getAnnouncements({ page, limit });

      if (response.success) {
        if (page === 1) {
          appStore.setAnnouncements(response.data.announcements);
        } else {
          appStore.addAnnouncements(response.data.announcements);
        }

        return { success: true, data: response.data };
      } else {
        error.value = response.message || "加载公告失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "加载公告失败";
      return { success: false, message: error.value };
    }
  };

  /**
   * 标记通知为已读
   */
  const markNotificationAsRead = async (notificationId: string) => {
    try {
      const response =
        await appApiService.markNotificationAsRead(notificationId);

      if (response.success) {
        appStore.markNotificationAsRead(notificationId);
        return { success: true };
      } else {
        error.value = response.message || "标记已读失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "标记已读失败";
      return { success: false, message: error.value };
    }
  };

  /**
   * 批量标记通知为已读
   */
  const markAllNotificationsAsRead = async () => {
    try {
      const response = await appApiService.markAllNotificationsAsRead();

      if (response.success) {
        appStore.markAllNotificationsAsRead();
        return { success: true };
      } else {
        error.value = response.message || "批量标记已读失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "批量标记已读失败";
      return { success: false, message: error.value };
    }
  };

  /**
   * 标记公告为已读
   */
  const markAnnouncementAsRead = async (announcementId: string) => {
    try {
      const response =
        await appApiService.markAnnouncementAsRead(announcementId);

      if (response.success) {
        appStore.markAnnouncementAsRead(announcementId);
        return { success: true };
      } else {
        error.value = response.message || "标记已读失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "标记已读失败";
      return { success: false, message: error.value };
    }
  };

  /**
   * 删除通知
   */
  const deleteNotification = async (notificationId: string) => {
    try {
      const response = await appApiService.deleteNotification(notificationId);

      if (response.success) {
        appStore.removeNotification(notificationId);
        return { success: true };
      } else {
        error.value = response.message || "删除通知失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "删除通知失败";
      return { success: false, message: error.value };
    }
  };

  /**
   * 清空所有通知
   */
  const clearAllNotifications = async () => {
    try {
      const response = await appApiService.clearAllNotifications();

      if (response.success) {
        appStore.clearAllNotifications();
        return { success: true };
      } else {
        error.value = response.message || "清空通知失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "清空通知失败";
      return { success: false, message: error.value };
    }
  };

  /**
   * 加载系统设置
   */
  const loadSystemSettings = async () => {
    try {
      const response = await appApiService.getSystemSettings();

      if (response.success) {
        appStore.setSystemSettings(response.data);
        return { success: true, data: response.data };
      } else {
        error.value = response.message || "加载系统设置失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "加载系统设置失败";
      return { success: false, message: error.value };
    }
  };

  /**
   * 更新系统设置
   */
  const updateSystemSettings = async (settings: any) => {
    try {
      const response = await appApiService.updateSystemSettings(settings);

      if (response.success) {
        appStore.setSystemSettings(response.data);
        return { success: true, data: response.data };
      } else {
        error.value = response.message || "更新系统设置失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "更新系统设置失败";
      return { success: false, message: error.value };
    }
  };

  /**
   * 加载功能限制
   */
  const loadFeatureLimits = async () => {
    try {
      const response = await appApiService.getFeatureLimits();

      if (response.success) {
        appStore.setFeatureLimits(response.data);
        return { success: true, data: response.data };
      } else {
        error.value = response.message || "加载功能限制失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "加载功能限制失败";
      return { success: false, message: error.value };
    }
  };

  /**
   * 检查功能是否可用
   */
  const checkFeatureAvailable = (feature: string): boolean => {
    const limits = featureLimits.value;
    if (!limits || !limits[feature]) return true;

    const limit = limits[feature];
    if (limit.enabled === false) return false;
    if (limit.maxUsage && limit.currentUsage >= limit.maxUsage) return false;

    return true;
  };

  /**
   * 获取功能使用情况
   */
  const getFeatureUsage = (feature: string) => {
    const limits = featureLimits.value;
    if (!limits || !limits[feature]) return null;

    const limit = limits[feature];
    return {
      current: limit.currentUsage || 0,
      max: limit.maxUsage || 0,
      percentage: limit.maxUsage
        ? Math.round((limit.currentUsage / limit.maxUsage) * 100)
        : 0,
      remaining: limit.maxUsage
        ? Math.max(0, limit.maxUsage - limit.currentUsage)
        : Infinity,
    };
  };

  /**
   * 报告错误
   */
  const reportError = async (error: any, context?: any) => {
    try {
      const errorData = {
        message: error.message || String(error),
        stack: error.stack,
        url: window.location.href,
        userAgent: navigator.userAgent,
        timestamp: new Date().toISOString(),
        userId: userStore.user?.id,
        context,
      };

      const response = await appApiService.reportError(errorData);

      if (response.success) {
        return { success: true, data: response.data };
      } else {
        console.error("Failed to report error:", response.message);
        return { success: false, message: response.message };
      }
    } catch (err: any) {
      console.error("Failed to report error:", err);
      return { success: false, message: err.message };
    }
  };

  /**
   * 启动心跳检测
   */
  const startHeartbeat = () => {
    if (heartbeatInterval.value) {
      clearInterval(heartbeatInterval.value);
    }

    heartbeatInterval.value = window.setInterval(async () => {
      try {
        await loadSystemStatus();
      } catch (err) {
        console.error("Heartbeat failed:", err);
      }
    }, APP_CONFIG.HEARTBEAT_INTERVAL);
  };

  /**
   * 停止心跳检测
   */
  const stopHeartbeat = () => {
    if (heartbeatInterval.value) {
      clearInterval(heartbeatInterval.value);
      heartbeatInterval.value = null;
    }
  };

  /**
   * 检查更新
   */
  const checkForUpdates = async () => {
    try {
      const response = await appApiService.checkUpdates();

      if (response.success) {
        return { success: true, data: response.data };
      } else {
        error.value = response.message || "检查更新失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "检查更新失败";
      return { success: false, message: error.value };
    }
  };

  /**
   * 获取系统日志
   */
  const getSystemLogs = async (options: any = {}) => {
    try {
      const response = await appApiService.getSystemLogs(options);

      if (response.success) {
        return { success: true, data: response.data };
      } else {
        error.value = response.message || "获取日志失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "获取日志失败";
      return { success: false, message: error.value };
    }
  };

  /**
   * 清理缓存
   */
  const clearCache = async (type?: string) => {
    try {
      const response = await appApiService.clearCache({ type });

      if (response.success) {
        return { success: true, data: response.data };
      } else {
        error.value = response.message || "清理缓存失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "清理缓存失败";
      return { success: false, message: error.value };
    }
  };

  /**
   * 创建备份
   */
  const createBackup = async (options: any = {}) => {
    try {
      const response = await appApiService.createBackup(options);

      if (response.success) {
        return { success: true, data: response.data };
      } else {
        error.value = response.message || "创建备份失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "创建备份失败";
      return { success: false, message: error.value };
    }
  };

  /**
   * 恢复备份
   */
  const restoreBackup = async (backupId: string) => {
    try {
      const response = await appApiService.restoreBackup(backupId);

      if (response.success) {
        return { success: true, data: response.data };
      } else {
        error.value = response.message || "恢复备份失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "恢复备份失败";
      return { success: false, message: error.value };
    }
  };

  /**
   * 格式化系统状态显示
   */
  const formatSystemStatus = (status: SystemStatus) => {
    return {
      cpu: `${status.cpu.toFixed(1)}%`,
      memory: `${status.memory.toFixed(1)}%`,
      disk: `${status.disk.toFixed(1)}%`,
      uptime: formatTimestamp(status.uptime),
      connections: status.connections.toLocaleString(),
      requests: status.requests.toLocaleString(),
    };
  };

  /**
   * 处理网络状态变化
   */
  const handleOnlineStatusChange = () => {
    isOnline.value = navigator.onLine;

    if (isOnline.value) {
      // 重新连接时重新加载数据
      loadSystemStatus();
      if (userStore.isAuthenticated) {
        loadNotifications();
      }
    }
  };

  // 生命周期钩子
  onMounted(() => {
    // 监听网络状态变化
    window.addEventListener("online", handleOnlineStatusChange);
    window.addEventListener("offline", handleOnlineStatusChange);

    // 监听页面可见性变化
    document.addEventListener("visibilitychange", () => {
      if (!document.hidden && isOnline.value) {
        loadSystemStatus();
      }
    });
  });

  onUnmounted(() => {
    // 清理事件监听器
    window.removeEventListener("online", handleOnlineStatusChange);
    window.removeEventListener("offline", handleOnlineStatusChange);

    // 停止心跳检测
    stopHeartbeat();
  });

  return {
    // 状态
    isLoading,
    error,
    isOnline,
    lastHeartbeat,
    appInfo,
    systemStatus,
    notifications,
    announcements,
    unreadNotifications,
    unreadAnnouncements,
    unreadCount,
    systemHealth,
    isMaintenanceMode,
    systemSettings,
    featureLimits,

    // 方法
    initializeApp,
    loadAppInfo,
    loadSystemStatus,
    loadNotifications,
    loadAnnouncements,
    markNotificationAsRead,
    markAllNotificationsAsRead,
    markAnnouncementAsRead,
    deleteNotification,
    clearAllNotifications,
    loadSystemSettings,
    updateSystemSettings,
    loadFeatureLimits,
    checkFeatureAvailable,
    getFeatureUsage,
    reportError,
    startHeartbeat,
    stopHeartbeat,
    checkForUpdates,
    getSystemLogs,
    clearCache,
    createBackup,
    restoreBackup,
    formatSystemStatus,
  };
}
